package com.party.admin.web.controller.activity;

import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.admin.biz.activity.ActivityBizService;
import com.party.admin.biz.activity.ActivityDeleteBizService;
import com.party.admin.biz.asynexport.IAsynExportService;
import com.party.admin.biz.circle.CircleBizNewService;
import com.party.admin.biz.copartner.TargetCopartnerBizService;
import com.party.admin.biz.crowdfund.ProjectBizService;
import com.party.admin.biz.crowdfund.RepresentBizService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.gatherInfo.ItineraryBizService;
import com.party.admin.biz.system.MemberBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.annotation.UserOperate;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.activity.ActivityOutput;
import com.party.admin.web.dto.output.crowdfund.ProjectForActivityOutput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.*;
import com.party.core.model.city.Area;
import com.party.core.model.city.City;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilType;
import com.party.core.model.crowdfund.*;
import com.party.core.model.distributor.WithCount;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.member.*;
import com.party.core.model.notify.TargetTemplate;
import com.party.core.model.notify.TargetTemplateType;
import com.party.core.model.system.Dict;
import com.party.core.model.system.DictEnum;
import com.party.core.model.user.User;
import com.party.core.model.wechat.WechatMerchants;
import com.party.core.service.activity.*;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.activity.biz.CrowfundResourceBizService;
import com.party.core.service.circle.biz.CircleBizService;
import com.party.core.service.circle.biz.CircleMemberBizService;
import com.party.core.service.city.IAreaService;
import com.party.core.service.city.ICityService;
import com.party.core.service.copartner.ITargetCopartnerService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.counterfoil.biz.CounterfoilBizService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.gatherInfo.biz.GatherInfoMembersBizService;
import com.party.core.service.member.*;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.system.IDictService;
import com.party.core.service.user.IUserService;
import com.party.core.service.wechatPlatform.IWechatMerchantService;
import com.party.notify.notifyPush.servce.INotifySendService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 活动
 *
 * @author Administrator
 *
 */

@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/activity/activity")
public class ActivityController {

	@Autowired
	private IActivityService activityService;

	@Autowired
	private IActivityInfoService activityInfoService;

	@Autowired
	private IActivityDetailService activityDetailService;

	@Autowired
	private IDictService dictService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IMemberActService memberActService;

	@Autowired
	private ICityService cityService;

	@Autowired
	private IOrderFormService orderFormService;

	@Autowired
	private FileBizService fileBizService;

	@Autowired
	private IProjectService projectService;

	@Autowired
	private ActivityBizService activityBizService;

	@Autowired
	private ICrowfundResourcesService crowfundResourcesService;

	@Autowired
	private ProjectBizService projectBizService;

	@Autowired
	private RepresentBizService representBizService;

	@Autowired
	private INotifySendService notifySendService;

	@Autowired
	private ActivityDetailBizService activityDetailBizService;

	@Autowired
	private CrowfundResourceBizService crowfundResourceBizService;

	@Autowired
	private CounterfoilBizService counterfoilBizService;

	@Autowired
	private ICounterfoilBusinessService counterfoilBusinessService;

	@Autowired
	private ICounterfoilService counterfoilService;

	@Autowired
	private IAreaService areaService;

	@Autowired
	private CircleMemberBizService circleMemberBizService;

	@Autowired
	private CircleBizService circleBizService;

	@Autowired
	private OrderActivityBizService orderActivityBizService;

	@Autowired
	private ICrowdfundEventService crowdfundEventService;

	@Autowired
	private StringJedis stringJedis;

	@Autowired
	private ITargetTemplateService targetTemplateService;

	@Autowired
	private ITargetCopartnerService targetCopartnerService;

	@Autowired
	private TargetCopartnerBizService targetCopartnerBizService;

	@Autowired
	private CosBizService cosBizService;

	@Autowired
	private GatherInfoMembersBizService gatherInfoMembersBizService;

	@Autowired
	private IThirdMemberService thirdMemberService;
	@Autowired
	private MemberBizService memberBizService;
	@Autowired
	private GatherProjectBizService gatherProjectBizService;
	@Autowired
	private ActivityDeleteBizService activityDeleteBizService;
	@Autowired
	private ItineraryBizService itineraryBizService;
	@Autowired
	private CircleBizNewService circleBizNewService;

	@Resource(name = "representAsynExportService")
	private IAsynExportService representAsynExportService;

	@Resource(name = "projectAsynExportService")
	private IAsynExportService projectAsynExportService;

	@Autowired
	private ISupportService supportService;

	@Autowired
	private IMemberExternalAppService memberExternalAppService;

	@Autowired
	private IWechatMerchantService wechatMerchantService;

	@Autowired
	private ISupportTransferService supportTransferService;

	@Autowired
	private IMemberAdministratorService memberAdministratorService;

	@Autowired
	private IEventGradationService eventGradationService;

	@Autowired
	private IMemberGroupService memberGroupService;

	protected static Logger logger = LoggerFactory.getLogger(ActivityController.class);


	/**
	 * 跳转至发布 普通活动
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "activityForm")
	public ModelAndView activityForm(String id) {
		ModelAndView mv = new ModelAndView("activity/activityForm");
		City city = new City();
		city.setIsOpen(1);
		mv.addObject("citys", cityService.list(city));
		Dict dict = new Dict();
		dict.setType(DictEnum.ACTIVITY_TYPE.getCode());
		mv.addObject("types", dictService.list(dict));
		if (StringUtils.isNotEmpty(id)) {
			Activity activity = activityService.get(id);
			City myCity = cityService.get(activity.getCityId());
			if (myCity != null) {
				mv.addObject("cityName", myCity.getName());
			}
			ActivityDetail activityDetail = activityDetailService.getByRefId(activity.getId());
			if (activityDetail != null) {
				activityDetailBizService.castToHTML(activityDetail);
			}
			mv.addObject("activity", activity);
			mv.addObject("activityDetail", activityDetail);

			Counterfoil t = new Counterfoil();
			t.setBusinessId(id);
			List<Counterfoil> counterfoils = counterfoilService.list(t);
			for (Counterfoil counterfoil : counterfoils) {
				if (counterfoil.getJoinNum() > 0) {
					counterfoil.setHasBuy(true);
				}
			}
			mv.addObject("counterfoils", counterfoils);

			Map<String, Object> resultMap = gatherProjectBizService.getProjectBiz(activity.getId());
			mv.addAllObjects(resultMap);
		}
		Map<Integer, String> counterTypes = CounterfoilType.convertMap();
		mv.addObject("counterTypes", counterTypes);
		mv.addObject("isGoods", false);
		return mv;
	}

	/**
	 * 跳转至发布 普通活动
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "zcActivityForm")
	public ModelAndView zcActivityForm(String id) {
		ModelAndView mv = new ModelAndView("activity/zcActivityFormNew");
		if (StringUtils.isNotEmpty(id)) {
			/** 活动 **/
			Activity activity = activityService.get(id);
			ActivityOutput activityOutput = ActivityOutput.transform(activity);
			String address = activityService.getShowAddress(activity);
			mv.addObject("address", address);
			// 跑马灯
			List<CrowfundResources> picList = crowfundResourcesService.findByRefId(activity.getId(), "1");
			mv.addObject("picList", picList);
			// 视频
			List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(activity.getId(), "2");
			if (videoList.size() > 0) {
				mv.addObject("video", videoList.get(0));
			}
			mv.addObject("activity", activityOutput);

			/** 活动详情 **/
			ActivityDetail activityDetail = activityDetailService.getByRefId(activity.getId());
			if (activityDetail != null) {
				activityDetailBizService.castToHTML(activityDetail);
			}
			mv.addObject("activityDetail", activityDetail);

			MemberGroup createBy = memberGroupService.get(activity.getMember());
			mv.addObject("createBy", createBy);

//			if (YesNoStatus.YES.getCode().equals(activity.getIsCopartner())) {
//				TargetCopartner targetCopartner = targetCopartnerService.findByTargetId(activity.getId());
//				mv.addObject("targetCopartner", targetCopartner);
//			}

			ThirdMember thirdMember = thirdMemberService.findByTargetId(activity.getId());
			mv.addObject("thirdMember", thirdMember);

			CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
			mv.addObject("crowdfundEvent", crowdfundEvent);

			List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(crowdfundEvent.getId(), Constant.BUSINESS_TYPE_CROWDFUND);
			mv.addObject("counterfoils", counterfoils);
		} else {
			CrowdfundEvent crowdfundEvent = new CrowdfundEvent();
			crowdfundEvent.setProgress(YesNoStatus.YES.getCode()); // 进行中
			Map<String, Object> params = Maps.newHashMap();
			params.put("openStatus", 1);
			crowdfundEvent.setCheckStatus(1);//审核通过的主题才能显示出来
			List<CrowdfundEvent> crowdfundEventList = crowdfundEventService.listWithParams(crowdfundEvent, params);
			mv.addObject("crowdfundEventList", crowdfundEventList);
		}
		return mv;
	}

	/**
	 * 跳转至详情 普通活动
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "activityDetail")
	public ModelAndView activityDetail(String id) {
		ModelAndView mv = new ModelAndView("activity/activityDetail");
		Activity activity = activityService.get(id);
		mv.addObject("activity", activity);
		ActivityDetail activityDetail = activityDetailService.getByRefId(id);
		if (activityDetail != null) {
			activityDetailBizService.castToHTML(activityDetail);
		}
		List<Counterfoil> counterfoils = counterfoilBizService.getActivityCounterfoils(id);
		if (counterfoils.size() > 0) {
			// 获取票价
			String newPrice = counterfoilBizService.getShowPrice(null, id);
			mv.addObject("newPrice", newPrice);
		} else {
			mv.addObject("newPrice", activity.getPrice().toString());
		}
		mv.addObject("activityDetail", activityDetail);
		return mv;
	}

	@RequestMapping(value = "zcActivityDetail")
	public ModelAndView zcActivityDetail(String actId) {
		ModelAndView mv = new ModelAndView("activity/zcActivityDetail");
		Activity activity = activityService.get(actId);

		ActivityDetail activityDetail = activityDetailService.getByRefId(actId);
		if (activityDetail != null) {
			activityDetailBizService.castToHTML(activityDetail);
		}

		CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
		if (null != crowdfundEvent) {
			List<EventGradation> eventGradations = eventGradationService.withCityNameByEventId(crowdfundEvent.getId());
			mv.addObject("eventGradations", eventGradations);
		}

		// 众筹金额
		Double actualAmount = projectService.getTotalAmountForTargetId(actId);

		//浏览量
		Integer viewNum = activityService.crowdfundView(actId);
		String address =activityService.getShowAddress(activity);
		mv.addObject("activity", activity);
		mv.addObject("actualAmount", actualAmount);
		mv.addObject("activityDetail", activityDetail);
		mv.addObject("viewNum", viewNum);
		mv.addObject("address", address);
		return mv;
	}

	/**
	 * 活动管理
	 * @param activity
	 * @param page
	 * @param commonInput
	 * @param s_start
	 * @param s_end
	 * @return
	 */
	@RequestMapping(value = "activityList")
	public ModelAndView activityList(ActivityWithMemberPartner activity, Page page, CommonInput commonInput, String s_start, String s_end) {
		if (null == commonInput.getTimeStatus()) {
			commonInput.setTimeStatus(YesNoStatus.NO.getCode());
		}
		ModelAndView mv = new ModelAndView("activity/activityList");
		activity.setIsCrowdfunded(0); // 普通活动
		Map<String, Object> params = CommonInput.appendParams(commonInput);

		mv.addObject("input", commonInput);
		// 活动开始时间
		if (StringUtils.isNotEmpty(s_start)) {
			params.put("s_start", s_start);
			mv.addObject("s_start", s_start);
		}
		if (StringUtils.isNotEmpty(s_end)) {
			params.put("s_end", s_end);
			mv.addObject("s_end", s_end);
		}

		Dict dict = new Dict();
		dict.setType(DictEnum.CHECK_STATUS.getCode());
		mv.addObject("checkStatus", dictService.list(dict));

		activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		List<ActivityWithMemberPartner> activities = activityService.webListPage(activity, params, page);
		List<ActivityOutput> activityOutputs = LangUtils.transform(activities, input -> {
			ActivityOutput output = ActivityOutput.transform(input);
			// 报名人数
			List<Counterfoil> counterfoils = counterfoilBizService.getActivityCounterfoils(input.getId());
			Activity dbActivity = activityService.get(input.getId());
			if (counterfoils.size() > 0) {
				String newPrice = counterfoilBizService.getShowPrice(counterfoils, input.getId());
				output.setNewPrice(newPrice);
			} else {
				dbActivity = orderActivityBizService.updateActivityInfo(input.getId());
				output.setNewPrice(dbActivity.getPrice().toString());
			}
			output.setJoinNum(dbActivity.getJoinNum());
			output.setLimitNum(dbActivity.getLimitNum());

			String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "activity");

			// 活动二维码
			String detailFileName = "detail_" + input.getId();
			String qrcodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
			output.setQrCodeUrl(qrcodeUrl);

			// 签到二维码
			String signFileName = "sign_" + input.getId();
			String bmQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + signFileName);
			output.setBmQrCodeUrl(bmQrCodeUrl);

			// 分销二维码
/*			String fxFileName = "fx_" + input.getId();
			String fxQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fxFileName);
			output.setDisQrCode(fxQrCodeUrl);*/
			return output;
		});

		mv.addObject("activities", activityOutputs);
		mv.addObject("page", page);
		mv.addObject("activity", activity);
		return mv;
	}

	/**
	 * 众筹活动管理
	 * @param activity
	 * @param page
	 * @param commonInput
	 * @param e_start
	 * @param e_end
	 * @return
	 */
	@RequestMapping(value = "zcActivityList")
	public ModelAndView zcActivityList(ActivityWithMemberPartner activity, Page page, CommonInput commonInput,
									   String e_start, String e_end, String eventName, Integer isMultiple) {
		ModelAndView mv = new ModelAndView("activity/zcActivityList");
		activity.setIsCrowdfunded(1); // 众筹活动
		Map<String, Object> param = CommonInput.appendParams(commonInput);

		mv.addObject("input", commonInput);
		// 报名截止时间
		if (StringUtils.isNotEmpty(e_start)) {
			param.put("e_start", e_start);
			mv.addObject("e_start", e_start);
		}
		if (StringUtils.isNotEmpty(e_end)) {
			param.put("e_end", e_end);
			mv.addObject("e_end", e_end);
		}
		param.put("eventName", eventName);
		param.put("isMultiple", isMultiple);
		mv.addObject("eventName", eventName);
		mv.addObject("isMultiple", isMultiple);

		Dict dict = new Dict();
		dict.setType(DictEnum.CHECK_STATUS.getCode());
		mv.addObject("checkStatus", dictService.list(dict));

		activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);

		param.put("openStatus", 1);

		Map<String, Object> params = RealmUtils.getMemberAdministrator(param,memberAdministratorService);

		List<ActivityWithMemberPartner> activities = activityService.webListPage(activity, params, page);
		List<ActivityOutput> activityOutputs = LangUtils.transform(activities, input -> {
			ActivityOutput output = ActivityOutput.transform(input);
			String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "zcActivity");

			Double actualAmount = projectService.getTotalAmountForTargetId(input.getId());
			output.setTotalMoney(actualAmount);

			Integer isMultipleNew = input.getIsMultiple();

			// 众筹联合发起二维码
			String dyFileName = "dy_" + input.getId();
			String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + dyFileName);
			output.setQrCodeUrl(qrCodeUrl);

			// 众筹项目详情二维码
			String detailFileName = "detail_" + input.getId();
			String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
			output.setBmQrCodeUrl(detailQrCodeUrl);

			if (YesNoStatus.NO.getCode().equals(isMultipleNew)) {
				Activity addressActivity = new Activity();
				addressActivity.setCityId(input.getCityId());
				addressActivity.setArea(input.getArea());
				addressActivity.setPlace(input.getPlace());
				String address = activityService.getShowAddress(addressActivity);
				output.setPlace(address);

				// 众筹直接付款二维码
				String payFileName = "directPay_" + input.getId();
				String payBySelfQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + payFileName);
				output.setPayBySelfQrCodeUrl(payBySelfQrCodeUrl);
			}

			//以下查询当前活动的发起者是否为经过验证的系统用户
			MemberGroup member = memberGroupService.getPartner(input.getMemberId());
			MemberExternalApp memberExternalApp =
					memberExternalAppService.findByMemberIdAndDeployType(member.getId(), member.getDeployType());//deployType 配置类型(0:授权配置，1：填写配置)
			if (memberExternalApp != null) {
				WechatMerchants wechatMerchants = wechatMerchantService.get(memberExternalApp.getExternalMerchantId());
				if (wechatMerchants != null && wechatMerchants.getType() != null
						&& wechatMerchants.getType().equals(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM)) {
					output.setSystemCustomer(true);
				}
			}
			return output;
		});

		if (!Strings.isNullOrEmpty(activity.getEventId())){
			mv.addObject("removeEvent", true);
		}
		mv.addObject("activities", activityOutputs);
		mv.addObject("page", page);
		mv.addObject("activity", activity);
		mv.addObject("isCopartner", 0);
		return mv;
	}

	/**
	 * 发布保存
	 * @param activityInput
	 * @param activity
	 * @param result
	 * @param activityDetail
	 * @return
	 */
	@ResponseBody
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public AjaxResult save(ActivityInput activityInput, Activity activity, BindingResult result, ActivityDetail activityDetail, GatherProject gatherProject) {
		try {
			String publisher = "";
			String memberId = RealmUtils.getCurrentUser().getId();
			// 数据验证
			if (result.hasErrors()) {
				List<ObjectError> allErros = result.getAllErrors();
				return AjaxResult.error(allErros.get(0).getDefaultMessage());
			}

			if (StringUtils.isNotEmpty(activityInput.getStartDate())) {
				activity.setStartTime(DateUtils.parse(activityInput.getStartDate(), "yyyy-MM-dd HH:mm"));
			}
			if (StringUtils.isNotEmpty(activityInput.getEndDate())) {
				activity.setEndTime(DateUtils.parse(activityInput.getEndDate(), "yyyy-MM-dd HH:mm"));
			}
			if (activity.getLimitNum() == null) {
				activity.setLimitNum(0);
			}

			if (StringUtils.isNotEmpty(activityInput.getAreaInput())) {
				activity.setArea(activityInput.getAreaInput());
			}
			if (StringUtils.isNotEmpty(activityInput.getAreaSelect())) {
				activity.setArea(activityInput.getAreaSelect());
			}

			activity.setThirdPartyId("a287a2a4e8e94fe6bd5fb19cad345da6");// 活动供应商默认是同行者
			activity.setTitle(activity.getTitle().replace("\"", "“"));
			User user = userService.findByLoginName("admin");
			activity.setIsCopartner(2);
			activity.setCheckStatus("1");
			if (StringUtils.isNotEmpty(activity.getId())) {
				// 更新内容
				Activity t = activityService.get(activity.getId());// 从数据库取出记录的值
				MyBeanUtils.copyBeanNotNull2Bean(activity, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
				activityService.update(t);// 保存
				publisher = t.getMember();
			} else {// 新增表单保存
				if (activity.getPrice() == null) {
					activity.setPrice(new Float(0.0));
				}
				activity.setIsOpen(1); // 报名开启
				activity.setShareNum(0); // 分享数
				activity.setReadNum(0); // 阅读数
				activity.setJoinNum(0); // 报名数
				activity.setGoodNum(0); // 点赞数

				activity.setCreateBy(user.getId());
				activity.setUpdateBy(user.getId());
				activityService.insert(activity);// 保存
				publisher = activity.getMember();
			}

			/************* 详情 ****************/
			activityDetailBizService.saveBiz(activity.getId(), activityDetail);
			counterfoilBizService.saveBiz(activity.getCounterfoils(), activity.getId(), Constant.BUSINESS_TYPE_ACTIVITY, memberId);

			gatherProject.setType(GatherProject.TYPE_ACT);
			gatherProject.setTargetId(activity.getId());
			gatherProject.setCreateBy(publisher);
			gatherProject.setUpdateBy(publisher);
			gatherProject.setTitle(activity.getTitle() + "的报名信息收集");
			gatherProject.setPicture(activity.getPic());
			gatherProject.setContent(null);
			gatherProject.setId(null);
			gatherProjectBizService.saveProjectBiz(gatherProject);
			try {
				// 普通活动
				String filePath = fileBizService.getUploadCIPath(publisher, "activity");
				/*** 详情二维码 ***/
				String fileName = "detail_" + activity.getId();
				String content = "hd/hd_detail.html?hdId=" + activity.getId();
				fileBizService.uploadCloudOut(fileName, filePath, content, publisher);

				/*** 签到二维码 ***/

				String bmFileName = "sign_" + activity.getId();
				String bmContent = "hd/hdbm_sign.html?hdId=" + activity.getId();
				fileBizService.uploadCloudOut(bmFileName, filePath, bmContent, publisher);

				/*** 分销二维码 ***/
				String fxFileName = "fx_" + activity.getId();
				String fxContent = activityBizService.getDistributionUrl(activity.getId(), publisher);
				fileBizService.uploadCloudOut(fxFileName, filePath, fxContent, publisher);

				/*** 直接付款二维码 ***/
				String dpFileName = "directPay_" + activity.getId();
				String directPayContent = "project/target_client_detail.html?id=" + activity.getId()+"&dp=1";
				fileBizService.uploadCloudOut(dpFileName, filePath, directPayContent, publisher);

			} catch (Exception e) {
				logger.error("活动/众筹项目二维码生成异常", e);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("保存失败", e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error("保存失败");
		}
	}

	/**
	 * 逻辑删除
	 *
	 * @param id
	 * @return
	 */
	@ResponseBody
	@UserOperate(moduleName = "活动/众筹项目", behaviorType = BehaviorType.DELETE)
	@RequestMapping(value = "deleteLogic")
	public AjaxResult deleteLogic(String id) {
		try {
			if (StringUtils.isEmpty(id)) {
				return new AjaxResult(false);
			}

			MemberAct t = new MemberAct();
			t.setActId(id);
			List<MemberAct> memberActs = memberActService.list(t);
			// 没有人报名可以直接删除
			if (memberActs.size() == 0) {
//				TargetCopartner targetCopartner = targetCopartnerService.findByTargetId(id);
//				if (targetCopartner != null) {
//					return new AjaxResult(false, "已分配合伙人，不能删除");
//				}
				Activity activity = activityService.get(id);
				activity.setDelFlag(BaseModel.DEL_FLAG_DELETE);
				activityService.update(activity);
			} else {
				return new AjaxResult(false, "已有人报名，不能删除");
			}

			return new AjaxResult(true);
		} catch (Exception e) {
			logger.error("活动删除异常", e);
		}
		return new AjaxResult(false);
	}

	/**
	 * 删除
	 *
	 * @param id 活动id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "delete")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AjaxResult delete(String id) {
		boolean result = activityDeleteBizService.deleteActivityBiz(id);
		if (result) {
			return AjaxResult.success();
		} else {
			return AjaxResult.error("删除失败");
		}
	}

	/**
	 * 审核活动
	 */
	@ResponseBody
	@RequestMapping(value = "verify")
	public AjaxResult verify(String actId, String checkStatus) {
		try {
			if (StringUtils.isEmpty(actId)) {
				return new AjaxResult(false);
			}
			Activity entity = activityService.get(actId);
			if (entity != null) {
				entity.setCheckStatus(checkStatus);
				activityService.update(entity);
				// 消息推送
				if (StringUtils.isNotEmpty(entity.getMember())) {
					if ("1".equals(checkStatus)) {
						notifySendService.sendActivityPass(entity.getTitle(), entity.getId(), entity.getMember());
					} else {
						notifySendService.sendActivityRefuse(entity.getTitle(), entity.getId(), entity.getMember());
					}
				}
			}
			return new AjaxResult(true);
		} catch (Exception e) {
			logger.error("活动审核异常", e);
		}
		return new AjaxResult(false);
	}

	/**
	 * 众筹列表
	 * @param id 活动编号
	 * @param page 分页参数
	 * @param projectWithAuthor 众筹状态
	 * @return 输出视图
	 */
	@RequestMapping(value = "zcCrowdfundList")
	public ModelAndView crowdfundList(String id, ProjectWithAuthor projectWithAuthor, Page page){
		page.setLimit(20);
		ModelAndView modelAndView = new ModelAndView("activity/zcCrowdfund");
		if(Strings.isNullOrEmpty(id)){
			return modelAndView;
		}
		//管理员数据权限控制
		Map<String, Object> params = RealmUtils.getMemberAdministrator(new HashMap<>(),memberAdministratorService);
		if(params.containsKey("memberId")){
			projectWithAuthor.setMemberId(params.get("memberId").toString());
		}
		Activity activity = activityService.get(id);
        Integer isSuccess = projectWithAuthor.getIsSuccess();//先保存查询类型
//		TargetCopartner targetCopartner = targetCopartnerService.findByTargetId(activity.getId());

		projectWithAuthor.setTargetId(id);
		projectWithAuthor.setPayType(0);
		projectWithAuthor.setBrokerage(1f);

		if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
			projectWithAuthor.setIsSuccess(10);
		}
		List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, page, activity.getMember());
		//众筹金额
		float actualAmount = activityBizService.actualAmountForTargetId(id);

		Integer  transferNum = supportTransferService.getShiftToPeopleTotal(activity.getId());
		modelAndView.addObject("transferNum", transferNum==null?0:transferNum);

		modelAndView.addObject("activity", activity);
		modelAndView.addObject("actualAmount", actualAmount);
		modelAndView.addObject("crowdfundNum", page.getTotalCount());
		modelAndView.addObject("projectWithAuthor",projectWithAuthor);
        projectWithAuthor.setPayType(1);
        projectWithAuthor.setIsSuccess(null);

		ProjectWithAuthor author = new ProjectWithAuthor();
		author.setTargetId(id);
		author.setPayType(1);
        modelAndView.addObject("directPayNum",
				projectBizService.projectForActivityList(author,null).size());//直接付款众筹数量
		projectWithAuthor.setIsSuccess(isSuccess);
		modelAndView.addObject("list", projectForActivityOutputList);
//		modelAndView.addObject("targetCopartner", targetCopartner);
		modelAndView.addObject("page", page);

		modelAndView.addAllObjects(activityBizService.putZipInfo(Constant.PRE_ZIP_URL + "crowdfund" + id));
		return modelAndView;
	}


	/**
	 * 导出众筹列表
	 * @param id 目标编号
	 * @return
	 */
	@ResponseBody
	@UserOperate(moduleName = "众筹项目-数据查看-众筹列表", behaviorType = BehaviorType.EXPORT)
	@RequestMapping(value = "crowdfundListExport")
	public AjaxResult crowdfundListExport(String id, ProjectWithAuthor projectWithAuthor, HttpServletRequest request) {
		//管理员数据权限控制
		Map<String, Object> params = RealmUtils.getMemberAdministrator(new HashMap<>(), memberAdministratorService);
		if (params.containsKey("memberId")) {
			projectWithAuthor.setMemberId(params.get("memberId").toString());
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				projectAsynExportService.export(id, projectWithAuthor, request.getSession().getId());
			}
		}).start();
		return AjaxResult.success();
	}


	/**
	 * 联合发起列表
	 * @param id 活动编号
	 * @param page 分页参数
	 * @return 输出视图
	 */
	@RequestMapping(value = "zcRepresentList")
	public ModelAndView representList(String id, WithCount withCount, Page page){
		ModelAndView modelAndView = new ModelAndView("activity/zcRepresent");
		modelAndView.addObject("isMultiple", false);
		modelAndView.addAllObjects(representBizService.listForActivityCommon(page, withCount, id));
		return modelAndView;
	}

	/**
	 * 联合发起列表导出
	 * @param id 活动编号
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "representListExport")
	public AjaxResult representListExport(String id, WithCount withCount, HttpServletRequest request){
		new Thread(new Runnable() {
			@Override
			public void run() {
				representAsynExportService.export(id, withCount, request.getSession().getId());
			}
		}).start();
		return AjaxResult.success();
	}


	/**
	 * 直接付款列表
	 * @param id 活动编号
	 * @param page 分页参数
	 * @return 输出视图
	 */
	@RequestMapping(value = "zcDirectPayList")
	public ModelAndView zcDirectPayList(String id, ProjectWithAuthor projectWithAuthor, Page page){
		page.setLimit(20);
		Integer isSuccess = projectWithAuthor.getIsSuccess();//先保存查询类型
		ModelAndView modelAndView = new ModelAndView("activity/zcDirectPayList");
		Activity activity = activityService.get(id);
		modelAndView.addObject("activity", activity);

		projectWithAuthor.setPayType(1);
		projectWithAuthor.setTargetId(id);
		if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
			projectWithAuthor.setIsSuccess(10);
		}
		List<ProjectForActivityOutput> directPayList =
				projectBizService.projectForActivityList(projectWithAuthor, page, "");//直接付款众筹

		directPayList.stream().forEach(directPay -> {
			SupportWithMember supportWithMember = new SupportWithMember();
			supportWithMember.setProjectId(directPay.getId());
			List<SupportWithMember> tempList = supportService.findByProjectId(directPay.getId());
			if (tempList != null && tempList.size() > 0) {
				Support support = tempList.get(0);
				directPay.setSupportId(support.getId());
			}
			String filePath = fileBizService.getUploadCIPath("directPay", directPay.getAuthorId());
			String dpCodeUrl = cosBizService.getPreviewPictureUrl(filePath + directPay.getId());
			directPay.setQrCodeUrl(dpCodeUrl);//直接付款众筹详情二维码
			directPay.setUrl(projectBizService.getDirectPayUrl(directPay.getId()));//查看链接
		});
		Integer crowdfundNum = projectService.sizeForTargetId(id);//众筹人数
		float actualAmount = activityBizService.actualAmountForTargetId(id);//众筹金额
		projectWithAuthor.setIsSuccess(isSuccess);

		Integer  transferNum = supportTransferService.getShiftToPeopleTotal(activity.getId());

		modelAndView.addObject("transferNum", transferNum==null?0:transferNum);
		modelAndView.addObject("actualAmount", actualAmount);
		modelAndView.addObject("crowdfundNum", crowdfundNum);
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);
		modelAndView.addObject("list", directPayList);
		modelAndView.addAllObjects(activityBizService.putZipInfo(Constant.PRE_ZIP_URL + "zczjfk_crowdfund" + id));
		modelAndView.addObject("page", page);
		return modelAndView;
	}

	/**
	 * 直接付款列表导出
	 * @param id 活动编号
	 * @return
	 */
	@ResponseBody
	@UserOperate(moduleName = "众筹项目-数据查看-直接付款列表", behaviorType = BehaviorType.EXPORT)
	@RequestMapping(value = "directPayListExport")
	public AjaxResult directPayListExport(String id, ProjectWithAuthor projectWithAuthor, HttpServletRequest request){
		new Thread(new Runnable() {
			@Override
			public void run() {
				projectAsynExportService.exportDPData(id, projectWithAuthor, request.getSession().getId());
			}
		}).start();
		return AjaxResult.success();
	}

	/**
	 * 删除资源图片
	 * @param resourceId 资源ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "delZcActivityPic")
	public AjaxResult delZcActivityPic(String resourceId) {
		crowfundResourcesService.delete(resourceId);
		return AjaxResult.success();
	}

	/**
	 * 更新showFront
	 *
	 * @param showFront
	 * @param actId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "updateShowFront")
	public AjaxResult updateShowFront(String showFront, String actId) {
		Activity activity = activityService.get(actId);
		if (activity != null) {
			activity.setShowFront(Integer.valueOf(showFront));
			activityService.update(activity);
		}
		return AjaxResult.success();
	}

	/**
	 * 创建业务ID
	 *
	 * @param actId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "createCircle")
	public AjaxResult createCircle(String actId, String type) {
		try {
			Activity activity = activityService.get(actId);
			MemberAct memberAct = new MemberAct();
			memberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
			memberAct.setActId(actId);
			List<MemberAct> memberActs = new ArrayList<MemberAct>();
			if (type.equals("1")) { // 已成功
				memberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode());
				memberActs = memberActService.list(memberAct);
			} else if (type.equals("2")) {
				if (activity.getIsCrowdfunded() == 0) {
					memberActs = memberActService.list(memberAct); // 全部
				} else if (activity.getIsCrowdfunded() == 1) {
					Set<Integer> status = new HashSet<Integer>();
					// status.add(ActStatus.ACT_STATUS_CANCEL.getCode());
					// status.add(ActStatus.ACT_STATUS_NO_JOIN.getCode());
					memberActs = memberActService.getSuccessMemberAct(memberAct, status);
				}
			}

			List<String> memberIds = new ArrayList<String>();
			memberIds.add(activity.getMember());

			String remarks = activity.getTitle() + "——";
			if (activity.getIsCrowdfunded() == 0) {
				remarks += (type.equals("1") ? "已报名成功人员圈子" : "全部报名人员圈子");
			} else if (activity.getIsCrowdfunded() == 1) {
				remarks += (type.equals("1") ? "已众筹成功人员圈子" : "全部发起众筹人员圈子");
			}
			remarks = remarks.replace("\"", "“");
			activity.setRemarks(remarks);

			String circleId = circleBizService.createCircleBusiness(actId, activity, type);
			circleMemberBizService.circleMemberManage(memberActs, circleId, type, memberIds, RealmUtils.getCurrentUser().getId());

			circleBizNewService.uploadQrCode(activity.getMember(), circleId);

			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("生成圈子异常", e);
			return AjaxResult.error("生成圈子异常");
		}
	}

	/**
	 * 创建业务ID
	 *
	 * @param actId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "createGatherInfo")
	public AjaxResult createGatherInfo(String actId, String type) {
		try {
			MemberAct memberAct = new MemberAct();
			memberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
			memberAct.setActId(actId);
			if (type.equals("1")) { // 已成功
				memberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode());
			}
			List<MemberAct> memberActs = memberActService.list(memberAct); // 全部

			Activity activity = activityService.get(actId);
			String remarks = activity.getTitle() + "——" + (type.equals("1") ? "报名成功人员信息收集项目" : "全部报名人员信息收集项目");
			remarks = remarks.replace("\"", "“");
			activity.setRemarks(remarks);

			String projectId = gatherInfoMembersBizService.createGatherInfoProjectBusiness(actId, activity, type, activity.getMember());
			gatherInfoMembersBizService.addMember(projectId, memberActs, activity.getMember());

			itineraryBizService.uploadQrCode(activity.getMember(), projectId);

			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("生成人员信息收集项目异常", e);
			return AjaxResult.error("生成人员信息收集项目异常");
		}
	}

	/**
	 * 前端城市三级联动
	 *
	 * @param cityName
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getAreaByCityName")
	public List<Area> getAreaByCityName(String cityName) {
		List<Area> areas = areaService.getAreaByCityName(cityName);
		return areas;
	}


	/**
	 * 消息发送视图
	 * @param targetId 项目编号
	 * @return 交互数据
	 */
	@RequestMapping(value = "messageView")
	public ModelAndView messageView(String targetId, Integer type, String id, String behavior){
		ModelAndView modelAndView = new ModelAndView("/activity/messageView");
		TargetTemplate targetTemplate = null;

		if ("add".equals(behavior)) {
			targetTemplate = targetTemplateService.recently(targetId, type);
			if (null == targetTemplate){
				targetTemplate = new TargetTemplate();
				targetTemplate.setTargetId(targetId);
				targetTemplate.setType(type);
			}
		} else {
			targetTemplate = targetTemplateService.get(id);
		}
		Map<Integer, String> types = TargetTemplateType.convertMap(1);
		for (Map.Entry<Integer, String> entry : types.entrySet()) {
			Integer status;
			if (TargetTemplateType.ACT_STATUS_ALL.getCode().equals(entry.getKey())) {
				status = null;
			} else {
				status = entry.getKey() - 4;
			}
			Integer num = memberActService.countByActivity(targetId, status);
			entry.setValue(entry.getValue() + "(" + num + "人)");
		}
		modelAndView.addObject("types", types);
		modelAndView.addObject("behavior", behavior);
		modelAndView.addObject("targetTemplate", targetTemplate);
		return modelAndView;
	}

	/**
	 * 保存模板同时消息推送
	 *
	 * @param targetTemplate 目标模板
	 * @return 交互数据
	 */
	@ResponseBody
	@RequestMapping(value = "sendAndSave")
	public AjaxResult sendAndSave(TargetTemplate targetTemplate) {
		AjaxResult ajaxResult = new AjaxResult();
		try {
			activityBizService.sendAndSave(targetTemplate);
		} catch (BusinessException be) {
			ajaxResult.setSuccess(false);
			ajaxResult.setDescription(be.getMessage());
			logger.error("消息推送异常", be);
			return ajaxResult;
		} catch (Exception e) {
			ajaxResult.setSuccess(false);
			ajaxResult.setDescription("发送异常");
			logger.error("消息推送异常", e);
			return ajaxResult;
		}
		ajaxResult.setSuccess(true);
		return ajaxResult;
	}

	/**
	 * 消息推送
	 *
	 * @param id 目标模板id
	 * @return 交互数据
	 */
	@ResponseBody
	@RequestMapping(value = "send")
	public AjaxResult send(String id) {
		AjaxResult ajaxResult = new AjaxResult();
		try {
			activityBizService.send(id);
		} catch (BusinessException be) {
			ajaxResult.setSuccess(false);
			ajaxResult.setDescription(be.getMessage());
			logger.error("消息推送异常", be);
			return ajaxResult;
		} catch (Exception e) {
			ajaxResult.setSuccess(false);
			ajaxResult.setDescription("发送异常");
			logger.error("消息推送异常", e);
			return ajaxResult;
		}
		ajaxResult.setSuccess(true);
		return ajaxResult;
	}

	/**
	 * 消息推送-定时-活动
	 * @param targetTemplate
	 * @param sendTimeString: 格式为yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "sendQuartzForActivity")
	public AjaxResult sendQuartzForActivity(TargetTemplate targetTemplate, String sendTimeString, String behavior) {
		try {
			return activityBizService.sendQuartz(targetTemplate, sendTimeString, behavior, Constant.SEND_SHORT_MESSAGE_TYPE_ACTIVITY);
		} catch (Exception e) {
			logger.error("定时短信推送异常", e);
			return AjaxResult.error("定时短信推送异常");
		}
	}

	/*@ResponseBody
	@RequestMapping("test")
	public String testFor(String time) {
		try {
			String s = "2018_4_26_20_03_20";
			Date date = DateUtils.parse(time, "yyyy_MM_dd_HH_mm_ss");
			String cron = DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss");
			for (int i = 0; i < 50; i++) {
				TargetTemplate template = new TargetTemplate();
				template.setTemplate("第一个for循环的 i = " + i);
				template.setTargetId("ed305829b4e54841ac93ff067d22f82e");
				template.setType(7);
				sendQuartzForActivity(template, cron, "add");
			}
			for (int i = 0; i < 50; i++) {
				TargetTemplate template = new TargetTemplate();
				template.setTemplate("这里是第二个for循环哦哦哦哈哈的 i = " + i);
				template.setTargetId("ed305829b4e54841ac93ff067d22f82e");
				template.setType(7);
				sendQuartzForActivity(template, cron, "add");
			}
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>执行完了");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "ok";
	}*/

	/**
	 * 删除短信
	 * @param id: 模板id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "delQuartzForActivity")
	public AjaxResult delQuartzForActivity(String id) {
		try {
			return activityBizService.delQuartzForActivity(id);
		} catch (Exception e) {
			logger.error("删除定时短信异常", e);
			return AjaxResult.error("定时短信删除异常");
		}
	}

	@ResponseBody
	@RequestMapping("initActivityQrCode")
	public AjaxResult initActivityQrCode() {
		activityBizService.uploadActivityQrCodeCI();
		return AjaxResult.success();
	}

	@ResponseBody
	@RequestMapping("initZcActivityQrCode")
	public AjaxResult initZcActivityQrCode() {
		activityBizService.uploadZcActivityQrCodeCI();
		return AjaxResult.success();
	}

	/**
	 * 选择众筹项目
	 * @param page
	 * @return
	 */
	@RequestMapping("selectZcActivity")
	public ModelAndView selectZcActivity(Activity activity, Page page) {
		page.setLimit(5);
		activity.setIsCrowdfunded(1);
		activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		List<Activity> activities = activityService.listPage(activity, page);
		List<Map<String, Object>> mapList = LangUtils.transform(activities, new Function<Activity, Map<String, Object>>() {
			@Override
			public Map<String, Object> apply(Activity input) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("targetId", input.getId());
				map.put("targetName", input.getTitle());
				return map;
			}
		});
		ModelAndView mv = new ModelAndView("gift/selectProject");
		mv.addObject("mapList", mapList);
		mv.addObject("page", page);
		mv.addObject("requestUrl", "activity/activity/selectZcActivity.do");
		mv.addObject("mapSearch", activity);
		return mv;
	}

	/**
	 * 选择活动
	 * @param page
	 * @return
	 */
	@RequestMapping("selectActivity")
	public ModelAndView selectActivity(Activity activity, Page page) {
		page.setLimit(5);
		activity.setIsCrowdfunded(0);
		activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		List<Activity> activities = activityService.listPage(activity, page);
		List<Map<String, Object>> mapList = LangUtils.transform(activities, new Function<Activity, Map<String, Object>>() {
			@Override
			public Map<String, Object> apply(Activity input) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("targetId", input.getId());
				map.put("targetName", input.getTitle());
				return map;
			}
		});
		ModelAndView mv = new ModelAndView("gift/selectProject");
		mv.addObject("mapList", mapList);
		mv.addObject("page", page);
		mv.addObject("requestUrl", "activity/activity/selectActivity.do");
		mv.addObject("mapSearch", activity);
		return mv;
	}


	@ResponseBody
	@RequestMapping(value = "getDistribution")
	public AjaxResult getDistribution(ActivityInfo activityInfo) {
		try {
			if (com.party.common.utils.StringUtils.isEmpty(activityInfo.getActivityId())) {
				return AjaxResult.error("活动id未传入");
			}
			ActivityInfo oldActivityInfo = activityInfoService.findByActivityId(activityInfo.getActivityId());
			if (oldActivityInfo == null) {
				oldActivityInfo = new ActivityInfo();
				oldActivityInfo.setActivityId(activityInfo.getActivityId());
				oldActivityInfo.setIsDistribution(0);
				activityInfoService.insert(oldActivityInfo);
			}
			return AjaxResult.success("已获取当前活动的分销属性", oldActivityInfo);
		} catch (Exception e) {
			logger.error("设置当前活动的分销属性异常", e);
			return AjaxResult.error("设置当前活动的分销属性失败");
		}
	}


	/**
	 * 设置当前活动的分销属性
	 * @param actId
	 * @return
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "setDistribution")
	public AjaxResult setDistribution(ActivityInfo activityInfo) {
		try {
			if (com.party.common.utils.StringUtils.isEmpty(activityInfo.getActivityId())) {
				return AjaxResult.error("活动id未传入");
			}
			if (activityInfo.getIsDistribution() == 1) {
				if (activityInfo.getDirectBrokerage() == null || activityInfo.getIndirectBrokerage() == null) {
					return AjaxResult.error("请设置相关佣金");
				}
				if (activityInfo.getDirectBrokerage() <= 0) {
					return AjaxResult.error("设置的一级佣金应大于0元");
				}
				if (activityInfo.getIndirectBrokerage() <= 0) {
					return AjaxResult.error("设置的下级佣金应大于0元");
				}
			}
			ActivityInfo oldActivityInfo = activityInfoService.findByActivityId(activityInfo.getActivityId());
			if (oldActivityInfo == null)//没有设置分销属性
				activityInfoService.insert(activityInfo);
			else {//已经设置过分销属性
				activityInfo.setId(oldActivityInfo.getId());
				activityInfoService.update(activityInfo);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("设置当前活动的分销属性异常", e);
			return AjaxResult.error("设置当前活动的分销属性失败");
		}
	}

	/**
	 * 转入的人列表
	 *
	 * @param id
	 *            活动编号
	 * @param projectWithAuthor
	 *            众筹信息
	 * @param page
	 *            分页参数
	 * @return 输出视图
	 */
	@RequestMapping(value = "zcShiftToPeopleList")
	public ModelAndView zcShiftToPeopleList(String id, ProjectWithAuthor projectWithAuthor, Page page) {
		page.setLimit(20);
		ModelAndView modelAndView = new ModelAndView("activity/zcShiftToPeople");
		Activity activity = activityService.get(id);

		projectWithAuthor.setTargetId(id);
		projectWithAuthor.setTransferP(true);
		List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectTransferForActivityList(projectWithAuthor, page, RealmUtils.getCurrentUser().getId());

		// 众筹金额
		float actualAmount = activityBizService.actualAmountForTargetId(id);

		//获取转入的人
		Integer  transferNum = supportTransferService.getShiftToPeopleTotal(activity.getId());


		ProjectWithAuthor dpAuthor = new ProjectWithAuthor();
		dpAuthor.setTargetId(id);
		dpAuthor.setPayType(1);
		List<ProjectForActivityOutput> dpProjectForActivityOutputList = projectBizService.projectForActivityList(dpAuthor, null, RealmUtils.getCurrentUser().getId());
		modelAndView.addObject("directPayNum", dpProjectForActivityOutputList.size());

		modelAndView.addObject("transferNum", transferNum==null?0:transferNum);
		modelAndView.addObject("activity", activity);
		modelAndView.addObject("actualAmount", actualAmount);
		modelAndView.addObject("crowdfundNum", projectService.sizeForTargetId(id));
		modelAndView.addObject("list", projectForActivityOutputList);
		modelAndView.addAllObjects(activityBizService.putZipInfo(Constant.PRE_ZIP_URL + "zczr_crowdfund" + id));
		modelAndView.addObject("page", page);
		return modelAndView;
	}
	/**
	 * 导出转入列表
	 *
	 * @param id
	 *            目标编号
	 * @return
	 */
	@ResponseBody
	@UserOperate(moduleName = "众筹项目-数据查看-转入列表", behaviorType = BehaviorType.EXPORT)
	@RequestMapping(value = "zcShiftToPeopleListExport")
	public AjaxResult zcShiftToPeopleListExport(String id, ProjectWithAuthor projectWithAuthor, HttpServletRequest request) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				projectWithAuthor.setTransferP(true);
				projectAsynExportService.exportTransferData(id, projectWithAuthor, request.getSession().getId());
			}
		}).start();
		return AjaxResult.success();
	}

	/**
	 * 获取城市
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getCitys")
	public List<City> getCitys() {
		City city = new City();
		city.setIsOpen(1);
		List<City> citys = cityService.list(city);
		return citys;
	}

	@RequestMapping(value = "selectActivityNew")
	public ModelAndView selectActivity(ActivityWithMemberPartner activity, Page page) {
		ModelAndView mv = new ModelAndView("activity/selectActivity");
		activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		activity.setIsCrowdfunded(0);
		Map<String, Object> params = Maps.newHashMap();
		List<ActivityWithMemberPartner> activities = activityService.webListPage(activity, params, page);
		mv.addObject("activities", activities);
		mv.addObject("page", page);
		mv.addObject("activity", activity);
		return mv;
	}
}
